<!--
 * @Author: C.
 * @Date: 2023-12-08 10:11:59
-->
<template>
  <view class="runtime-bar-wrapper">
    <canvas :id="canvasId" :canvas-id="canvasId" class="canvas-box" />
  </view>
</template>
<script lang="ts" setup>
// ----------------------------- 第三方引入 -----------------------------

import { getCurrentInstance, onMounted, ref, watch } from 'vue'
import { DeviceStateEnum } from '@/maps/device/DeviceStateEnum'

import { buildShortUUID } from '@/utils/uuid'
const canvasId = buildShortUUID('canvas_')
const ctx = uni.createCanvasContext(canvasId, getCurrentInstance())
const props = defineProps({
  timeList: {
    type: Array as PropType<Recordable[]>,
    default: () => [],
  },
})
const DataRef = ref<Recordable[]>(tansformData(props.timeList))
const widthRef = ref<any>(400)
function getWidth() {
  return new Promise((r) => {
    const info = uni
      .createSelectorQuery()
      .in(getCurrentInstance())
      .select(`#${canvasId}`)
    info
      .boundingClientRect((data: any) => {
        r(data.width - data.left)
      })
      .exec()
  })
}
function rectProcess(ctx: any, data: any[]) {
  // 预留边距
  const padding = 15
  // 可使画框
  const boxWidth = widthRef.value - 2 * padding
  // 时间单位 精确到分
  const timeUnit = 24 * 60
  const pxRate = boxWidth / timeUnit
  ctx.clearRect(0, 0, widthRef.value, 45)
  //绘制背景
  ctx.fillStyle = '#888'
  ctx.fillRect(padding, 0, boxWidth, 30)
  // 绘制刻度
  for (let i = 0; i <= 12; i++) {
    const start = (i * boxWidth) / 12 + padding
    ctx.moveTo(start, 30)
    ctx.lineTo(start, 35)
    ctx.stroke()
    ctx.font = 'bold 10px serif'
    ctx.fillStyle = '#000'
    ctx.textAlign = 'center'
    ctx.fillText(`${i * 2}:00`, start, 45)
  }
  // 画进度
  //开始点在第一个边距
  let start = padding
  data.forEach((item) => {
    ctx.fillStyle = item.color
    // 占比长度
    const len = item.timeDuring * pxRate
    // 结束点
    ctx.fillRect(start, 0, len, 30)
    // 将结束点 设为下一次开始点
    start = len + start
  })
  // 裁剪进度条形状
  // ctx.beginPath()

  ctx.draw()
}
function tansformData(list: Recordable[]) {
  return list.map((item) => {
    return {
      timeDuring: item.Miniute - 10 > 0 ? item.Miniute - 10 : item.Miniute,
      color: DeviceStateEnum.getItem(item.DeviceState)?.color,
    }
  })
}
async function renderChat() {
  //
  rectProcess(ctx, DataRef.value)
}
onMounted(async () => {
  widthRef.value = await getWidth()
  renderChat()
})
uni.onWindowResize(() => {
  renderChat()
})
watch(
  () => props.timeList,
  (v: Recordable[]) => {
    DataRef.value = tansformData(v)
    renderChat()
  }
)
</script>
<style lang="scss" scoped>
.runtime-bar-wrapper {
  width: 100%;
  @include flexBox();
  padding-left: 20rpx;
  .canvas-box {
    width: 100%;
    height: 50px;
  }
}
</style>
